<?php
/**
 * turn a two-byte int (little endian) into one "normal" int
 *
 * example: 0x4D 0x03 is 77d 03d. taking it by its displayed order
 * would give the wrong 19715. by using this function, it becomes
 * 845d (0x34D).
 * @param unknown_type $i1 the charcode of the lower-endian byte
 * @param unknown_type $i2 the charcode of the higher-endian byte
 * @return the integer
 */
function le_to_int($i1, $i2, $i3 = 0, $i4 = 0) {
	$s = 0;
	$s += $i4 * (pow(2,24));
	$s += $i3 * (pow(2,16));
	$s += $i2 * (pow(2,8));
	$s += $i1;
	return $s;
}

/**
 * get a char from the file
 * @param unknown_type $fp the file pointer
 * @param unknown_type $pos null-based seek position
 * @param unknown_type $as_is if true return a char, if false return its integer value
 */
function getchar($fp, $pos, $as_is = true) {
	fseek($fp, $pos, SEEK_SET);
	$len = fstat($fp);
	$len = $len["size"];
	if (feof($fp) || ftell($fp) >= $len)
		throw new Exception("Read behind file's end!");
	if ($as_is)
		return fgetc($fp);
	else
		return ord(fgetc($fp));

}

/**
 * turn a character code into a (R,G,B) color code (256-bit palette)
 * @param unknown_type $char character code (int 0-255)
 */
function rgb($char) {
	$r["r"]=$char;
	$r["g"]=$char;
	$r["b"]=$char;
	return $r;
}

/**
 * return a string as the hexcode which it is; used for debugging magicbyte problems
 * @param unknown_type $str the string
 */
function strtohex($str) {
	$ret="";
	for($i=0;$i<strlen($str);$i++)
		$ret.=str_pad(dechex(ord($str[$i])), 2,"0",STR_PAD_LEFT)." ";
	return $ret;
}
?>